package git.bankview.wl.common;

import java.util.*;
import java.text.*;
import java.sql.*;

import laya.semi.process.*;

import git.bankview.sl.db.*;

import org.apache.log4j.Logger;

public class UserOpLogActivity
	implements IGenericClassActivity
{
	private static Logger log = Logger.getLogger(UserOpLogActivity.class);
	
	private static int m_nLastLogId = 0;

	public void execute(IProcessContext oCtx)
		throws Exception
	{
		long nCurrent = new java.util.Date().getTime();
		Connection oConn = DBConnectionFactory.getCoreConnection();

		try
		{
			String[] vParam = oCtx.getActivityParameter().split(":");
			StringBuffer oSql = new StringBuffer("INSERT INTO UOPLOG VALUES");
			oSql.append("(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
			PreparedStatement ps = oConn.prepareStatement(oSql.toString());
			
			ps.setInt(1, getNewLogId());
			ps.setDate(2, new java.sql.Date(nCurrent));
			ps.setTime(3, new java.sql.Time(nCurrent));
			ps.setString(4, oCtx.getProcessName());
			ps.setString(5, oCtx.getActiveStateId());
			
			git.bankview.wl.bean.LogonBean oLogon = (git.bankview.wl.bean.LogonBean)oCtx.getField(vParam[0]);
			
			ps.setString(6, null == oLogon ? "<ERROR>" : oLogon.getUsername());
			ps.setString(7, null == oLogon ? "<ERROR>" : oLogon.getRemoteHost());
			
			for (int i = 1; i < 12; ++i)
			{
				ps.setObject(i + 7, getParam(vParam[i], oCtx));
			}
			
			vParam = vParam[12].split(",");
			StringBuffer oComplexTxt = new StringBuffer();
			
			for (int i = 0; i < vParam.length; ++i)
			{
				if (0 < i)
					oComplexTxt.append(",");
				oComplexTxt.append(getParam(vParam[i], oCtx));
			}
			ps.setString(19, oComplexTxt.toString());
			
			ps.executeUpdate();
		}
		catch(SQLException e)
		{
			log.warn("Exception while write log to database: ", e);
		}
		finally
		{
			oConn.close();
		}
	}
	
	private Object getParam(String param, IProcessContext oCtx)
		throws Exception
	{
		if ('#' == param.charAt(0))
			return param.substring(1);
			
		return oCtx.getField(param);
	}
	
	private synchronized static int getNewLogId()
		throws Exception
	{
		if (0 == m_nLastLogId)
		{
			Connection oConn = DBConnectionFactory.getCoreConnection();
			try
			{
				Statement st = oConn.createStatement();
				ResultSet rs = st.executeQuery("SELECT MAX(LOGSID) FROM UOPLOG");
				if (rs.next())
					m_nLastLogId = rs.getInt(1);
			}
			finally
			{
				oConn.close();
			}
		}
			
		return ++m_nLastLogId;
	}
}
